package asia.hymsk.spring.exception;

import asia.hymsk.spring.pojo.Response;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 花于陌上开
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @ExceptionHandler(Exception.class)
    public Response exception(Exception e) {
        e.printStackTrace(System.err);
        //获取请求方法和请求路径
        String method = request.getMethod();
        String path = request.getServletPath();
        //请求方法参数
        Object args = request.getParameterMap();
        String methodPara = JSONObject.toJSONString(args);
        //获取相应状态
        int status = response.getStatus();
        //日志记录
        log.error(String.format("[%s](%d) %s : %s", method, status, path, methodPara));
        return Response.error("异常错误，请联系管理员");
    }
}